<template>
  <section>
    <h1>Camera Preview</h1>
    <video controls ref="videoRef" width="640px" height="480px" autoplay></video>
    <el-button @click="startCamera">Start Camera</el-button>
    <el-button @click="stopCamera">Stop Camera</el-button>
  </section>
</template>
<script lang="ts" setup>
const stream = ref()
const videoRef = ref()
async function startCamera() {
  try {
    // 请求用户的摄像头权限
    stream.value = await navigator.mediaDevices.getUserMedia({
      audio: true,
      video: {
        width: { min: 1280 },
        height: { min: 720 }
      }
    })
    console.log(stream.value, 'stream.value', videoRef.value)

    // 将视频流赋值给video元素的srcObject属性

    console.log(stream.value, 'stream.value')

    videoRef.value.srcObject = stream.value
  } catch (error) {
    console.error('Error accessing camera:', error)
  }
}

function stopCamera() {
  // 停止并释放视频流
  if (stream.value) {
    console.log(stream.value.getTracks(), 'stream.value.getTracks()')

    stream.value.getTracks().forEach((track) => track.stop())

    stream.value = null
    videoRef.value.srcObject = null
  }
}

onBeforeUnmount(() => {
  // 在组件卸载前停止摄像头
  stopCamera()
})
</script>
<style lang="less" scoped>
video {
  transform: scaleX(-1);
  /* 如果需要，可以添加额外的样式来调整位置 */
  /* 例如：left: 0; transform-origin: 100% 50%; */
}
</style>
